package com.innovation.chengzhangriji.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.Parent;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Change;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.FileUploadResponse;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.http.TicketGetRequest;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.widget.CuteEditText;
import com.innovation.chengzhangriji.ui.widget.CuteTextView;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.util.List;

public class EditUserInfoActivity extends BaseActivity implements CuteToolbar.OnClickCuteToolbarListener, View.OnClickListener {

    private RoundedImageView imageHead;

    private CuteTextView textName;

    private CuteTextView textGender;

    private String name;

    private int gender;

    private int selectGender;

    private String url;

    private DisplayImageOptions options;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if(requestCode == Config.REQUEST_OPEN_CAMERA || requestCode == Config.REQUEST_OPEN_PHOTO) {
                String imageUrl = null;
                switch (requestCode) {
                    case Config.REQUEST_OPEN_CAMERA:
                        imageUrl = data.getStringExtra(Config.ACTION_EXTERNAL_RESULT_PHOTO);
                        break;
                    case Config.REQUEST_OPEN_PHOTO:
                        imageUrl = data.getStringExtra(Config.ACTION_EXTERNAL_RESULT_PHOTO);
                        break;
                }
                if (!TextUtils.isEmpty(imageUrl)) {
                    File imgFile = new File(imageUrl);
                    if (imgFile.exists()) {
                        ImageLoader.getInstance().displayImage("file://" + imageUrl, imageHead);
                        uploadPhoto(imageUrl);
                    }
                }
            } else if(requestCode == Config.ChangeBabySex) {
                gender = data.getStringExtra("sex").equals("男")? 1 : 2;
                textGender.setText(data.getStringExtra("sex"));
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LoginInfo oldLoginInfo = Config.getLoginInfo(this);
        if (oldLoginInfo == null) {
            return;
        }
        name = oldLoginInfo.getName();
        gender = oldLoginInfo.getGender();
        url = oldLoginInfo.getUrl();
        String phone = oldLoginInfo.getPhone();

        setContentView(R.layout.activity_edit_user_info);
        CuteToolbar toolbar = (CuteToolbar) findViewById(R.id.toolbar);
        toolbar.setOnClickCuteToolbarListener(this);

        RelativeLayout layoutPhoto = (RelativeLayout) findViewById(R.id.layout_photo);
        RelativeLayout layoutName = (RelativeLayout) findViewById(R.id.layout_name);
        RelativeLayout layoutGender = (RelativeLayout) findViewById(R.id.layout_gender);
        layoutPhoto.setOnClickListener(this);
        layoutName.setOnClickListener(this);
        layoutGender.setOnClickListener(this);

        imageHead = (RoundedImageView) findViewById(R.id.image_head);
        textName = (CuteTextView) findViewById(R.id.text_name);
        textGender = (CuteTextView) findViewById(R.id.text_gender);
        CuteTextView textPhone = (CuteTextView) findViewById(R.id.text_phone);

        imageHead.setOnClickListener(this);
        setOptions();
        ImageLoader.getInstance().displayImage(url, imageHead, options);
        textName.setText(name);
        textPhone.setText(phone);
        switch (oldLoginInfo.getGender()) {
            case 1:
                textGender.setText("男");
                break;
            case 2:
                textGender.setText("女");
                break;
        }
    }

    @Override
    public void onClickLeft() {
        if (TextUtils.isEmpty(name)) {
            tipShow("请填写昵称");
            return;
        }
        if (gender == 0 || gender == -1) {
            tipShow("请填写性别");
            return;
        }
        if (change()) {
            save();
        } else {
            finish();
        }
    }

    @Override
    public void onClickRight() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_photo:
                openDialog();
                break;
            case R.id.layout_name:
                openNameDialog();
                break;
            case R.id.layout_gender:
                openGenderDialog();
                break;
            case R.id.image_head:
                openHeadGallery();
                break;
        }
    }

    private boolean change() {

        LoginInfo loginInfo = Config.getLoginInfo(this);
        return loginInfo != null
                && (!loginInfo.getName().equals(name)
                || loginInfo.getGender() != gender
                || !loginInfo.getUrl().equals(url));
    }

    private void save() {
        LoginInfo loginInfo = Config.getLoginInfo(this);
        if (loginInfo == null) {
            finish();
            return;
        }
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        Change[] changeArray = new Change[3];
        changeArray[0] = new Change();
        changeArray[0].setKey("UserName");
        changeArray[0].setValue(name);
        changeArray[1] = new Change();
        changeArray[1].setKey("Sex");
        changeArray[1].setValue("" + gender);
        changeArray[2] = new Change();
        changeArray[2].setKey("LogoPath");
        changeArray[2].setValue(url);

        Client.requestAccountUpdate(this, phone, token, changeArray, new ResponseHandler() {

            @Override
            public void onInnovationStart() {
                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                LoginInfo loginInfo = Config.getLoginInfo(EditUserInfoActivity.this);
                if (loginInfo == null) {
                    return;
                }
                loginInfo.setName(name);
                loginInfo.setUrl(url);
                loginInfo.setGender(gender);
                Config.setLoginInfo(EditUserInfoActivity.this, new Gson().toJson(loginInfo));
                setResult(RESULT_OK);
                finish();
            }

            @Override
            public void onChZhRJFailure(String value) {
                tipShow(value);
            }

            @Override
            public void onInnovationFinish() {
                dismissProgressDialog();
            }

            @Override
            public void onInnovationExceptionFinish() {
                dismissProgressDialog();
            }

        }, networkUnavailableSampleImpl());
    }

    private void setOptions() {
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.ic_head_circle_default_small)    //在ImageView加载过程中显示图片
                .showImageForEmptyUri(R.drawable.ic_head_circle_default_small)  //image连接地址为空时
                .showImageOnFail(R.drawable.ic_head_circle_default_small)  //image加载失败
                .cacheOnDisk(true)   //加载图片时会在磁盘中加载缓存
                .build();
    }

    private void openDialog() {
        final CharSequence[] items = {"拍照", "从手机相册选择"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("修改头像");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                switch (item) {
                    case 0:
                        startHeadCameraForResult();
                        break;
                    case 1:
                        startHeadSelectForResult();
                        break;
                }
            }
        });
        builder.create().show();
    }

    private void startHeadCameraForResult() {
        Intent intent = new Intent(this, HeadCameraActivity.class);
        startActivityForResult(intent, Config.REQUEST_OPEN_CAMERA);
    }

    private void startHeadSelectForResult() {
        Intent intent = new Intent(this, HeadPhotoActivity.class);
        startActivityForResult(intent, Config.REQUEST_OPEN_PHOTO);
    }

    private void openNameDialog() {
        final CuteEditText editText = new CuteEditText(this);
        editText.setText(textName.getText());
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
        new AlertDialog.Builder(this).setTitle("修改昵称").setView(editText).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                name = editText.getText().toString();
                textName.setText(name);
            }
        }).setNegativeButton("取消", null).show();
    }

    private void openGenderDialog() {
        switch (gender) {
            case Client.BOY:
                selectGender = 0;
                break;
            case Client.GIRL:
                selectGender = 1;
                break;
        }
//        new AlertDialog.Builder(this).setTitle("修改性别")
//                .setSingleChoiceItems(new String[]{"男", "女"}, selectGender, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        selectGender = which;
//                    }
//                })
//                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        switch (selectGender) {
//                            case 0:
//                                gender = Client.BOY;
//                                textGender.setText("男");
//                                break;
//                            case 1:
//                                gender = Client.GIRL;
//                                textGender.setText("女");
//                                break;
//                        }
//                    }
//                }).show();
        Intent intent = new Intent(this, PetnameListActivity.class);
        intent.putExtra("type", "parent_sex");
        intent.putExtra("sex", new String[]{"男", "女"}[selectGender]);
        startActivityForResult(intent, Config.ChangeBabySex);
    }

    private void openHeadGallery() {
        if (TextUtils.isEmpty(url)) {
            openDialog();
            return;
        }
        Intent intent = new Intent(this, HeadGalleryDialogActivity.class);
        intent.putExtra("url", url);
        startActivity(intent);
    }

    private void uploadPhoto(String photoUrl) {
        LoginInfo login = Config.getLoginInfo(this);
        if (login == null) {
            return;
        }
        String phone = login.getPhone();
        String token = login.getToken().getAccessToken();
        Client.requestFileUpload(this, phone, token, TicketGetRequest.TYPE_IMAGE, "jpg", new File(photoUrl), new ResponseHandler() {

            @Override
            public void onInnovationStart() {
                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                FileUploadResponse response = get(value.toString(), FileUploadResponse.class);
                if (response == null) {
                    return;
                }
                url = response.getUrl();
            }

            @Override
            public void onInnovationFinish() {
                dismissProgressDialog();
            }

            @Override
            public void onInnovationExceptionFinish() {
                dismissProgressDialog();
            }

        }, networkUnavailableSampleImpl());
    }
}
